<template>
  <div class="mainBox">
    <div class="title">数据分类</div>
    <n-layout class="layout-wrapper">
      <n-layout has-sider sider-placement="left">
        <n-layout-sider :width="230" bordered :collapsed-width="64" show-trigger collapse-mode="width"
          @after-enter="afterEnter" @after-leave="afterLeave" :collapsed="collapsed" @collapse="collapsed = true"
          @expand="collapsed = false">
          <div class="uploadData">
            <div class="Classification" v-show="fold">分类</div>
            <div class="refresh" @click="clickRefresh">
              <n-button quaternary circle type="success">
                <template #icon>
                  <n-icon>
                    <Refresh />
                  </n-icon>
                </template>
              </n-button>
            </div>
            <div class="add" @click="addData">
              <n-button quaternary circle type="success">
                <template #icon>
                  <n-icon>
                    <Add />
                  </n-icon>
                </template>
              </n-button>
            </div>
          </div>

          <n-menu v-on:contextmenu="handleShowContextMenu" :collapsed-width="64" :collapsed-icon-size="22"
            :options="menusValue" :collapsed="collapsed" v-model:value="menuKey" @update:value="handleUpload" />
        </n-layout-sider>
        <n-layout-content>
          <div style="display: flex; height: calc(80vh - 10px)">
            <n-layout>
              <n-layout-content style="height: 100%">
                <!-- 右边组件 -->
                <content :imageList="imageList"></content>
              </n-layout-content>
            </n-layout>
          </div>
        </n-layout-content>
      </n-layout>
    </n-layout>

    <!-- 添加的模态框 -->
    <n-modal v-model:show="showModal" :mask-closable="false">
      <n-card style="width: 600px" title="添加分类" :bordered="false" size="huge" role="dialog" aria-modal="true">
        <div>
          <n-form ref="formRef" :model="model" :rules="rules">
            <n-form-item path="content" label="内容">
              <n-input v-model:value="model.content" @keydown.enter.prevent />
            </n-form-item>
          </n-form>
        </div>

        <template #footer>
          <div class="footer" style="display: flex;justify-content: end;">
            <n-button strong secondary type="error" style="margin-right: 10px;" @click="clickCancel">
              取消
            </n-button>
            <n-button strong secondary type="success" @click="clickAdd">
              添加
            </n-button>
          </div>
        </template>
      </n-card>
    </n-modal>

     <!-- 修改的模态框 -->
    <n-modal v-model:show="showModalTwo" :mask-closable="false">
      <n-card style="width: 600px" title="修改名称" :bordered="false" size="huge" role="dialog" aria-modal="true">
        <div>
          <n-form ref="formRef2" :model="modelTwo" :rules="rules">
            <n-form-item path="content" label="内容">
              <n-input v-model:value="modelTwo.content" @keydown.enter.prevent />
            </n-form-item>
          </n-form>
        </div>

        <template #footer>
          <div class="footer" style="display: flex;justify-content: end;">
            <n-button strong secondary type="error" style="margin-right: 10px;" @click="clickCancelTwo">
              取消
            </n-button>
            <n-button strong secondary type="success" @click="clickAddTwo">
              修改
            </n-button>
          </div>
        </template>
      </n-card>
    </n-modal>

  </div>
</template>

<script lang="ts" setup>
import { Component, h, ref, onMounted, render } from "vue";
import content from './content/index.vue'
import { getSpaceData, getPicData, addItemNameData, handlePicture, handleditorName } from "../../../api/funAPI"
import { deepCopy } from "../../../utils/unit"
import { Add, Refresh,Image } from "@vicons/ionicons5"
import emitter from '../../../utils/mitt'
import { NIcon, useMessage, useDialog, NEllipsis } from 'naive-ui'
// import { BookmarkOutline, Image, CloseOutline, Pencil } from '@vicons/ionicons5'
// import Item from "@/pages/editor/components/config-panel/components/item.vue";
//@ts-ignore
import ContextMenu from "@imengyu/vue3-context-menu";

const message = useMessage()
const dialog = useDialog()
const collapsed = ref(true)
const menuKey = ref("index");
const menusValue: any = ref([])  // 名称列表（用来渲染）
const getListData: any = ref([])  // 名称列表（用来处理数据）
const imageList: any = ref([])   // 图片集合
const showModal: any = ref(false)   // 添加名称的model框
const showModalTwo: any = ref(false) // 修改名称的model框
const fold = ref(false)   // 知道是否折叠然后控制分类这两个字显隐
const ItemName: any = ref()
const model = ref({   // 添加的模态框内容
  content: ''
})

const modelTwo = ref({  // 修改的模态框内容
  content: ''
})
const rules = {
  content: [
    {
      required: true,
      validator(rule: any, value: string) {
        if (!value) {
          return new Error('不能为空')
        }
        return true
      },
      trigger: ['input', 'blur']
    }
  ]
}   // 添加名称的验证规则
const formRef = ref()  // 添加的模态框的dpm
const formRef2 = ref() // 修改的模态框的dom

// 刷新
emitter.on('refresh', () => {
  handlePic(menuKey.value)
})

/**
 * @param e 为id
 * menu 选中菜单的回调
 */
const handleUpload = (e) => {
  handlePic(e)
}

// 鼠标右击事件
const handleShowContextMenu = (e: any) => {
  e.preventDefault();
  // 拿到name相同的数据
  const getData = getListData.value.find((item) => {
    if (item.name == e.target.innerText) {
      return item
    }
  })

  ContextMenu.showContextMenu({
    x: e.x,
    y: e.y,
    theme: "flat dark",
    items: [
      {
        label: "编辑",
        onClick: () => {
          handleClickTwo(getData)
        }
      },
      {
        label: "删除",
        onClick: () => {
          handleClick(getData)
        }
      },
    ],
  });
};

// 这个应该是打开新增的模态框
const addData = () => {
  showModal.value = true
}

// 处理图片
function renderIcon(icon: Component) {
  return () => h(NIcon, { size: 16 }, { default: () => h(icon) });
}

// 获取列表
const handleList = async () => {
  menusValue.value = []
  const data = await getSpaceData()
  getListData.value = data
  const copyData = deepCopy(data)
  copyData.map((item, index) => {
    menusValue.value.push({

      // label: () => h('div', { class: 'my-class' }, [
      //   h('div', { class: 'my-title' }, `${item.name}`),
      //   // h(NEllipsis, null, { default: () =>  `${item.name}`}),
      //   h('div', { class: 'includeDiv' }, [
      //     h('span', { class: 'icon-1', onClick: () => handleClickTwo(item) }, h(NIcon, { size: 14 }, { default: () => h(Pencil) })),
      //     h('span', { class: 'icon-2', onClick: () => handleClick(item) }, h(NIcon, { size: 14 }, { default: () => h(CloseOutline) }))
      //   ])
      // ]),
      label: item.name,
      key: item.id,
      icon: renderIcon(Image)
    })
  })
  menuKey.value = menusValue.value[0].key
  handlePic(menuKey.value)
}

// 弹出删除框
function handleClick(item) {
  dialog.warning({
    title: '提示',
    content: '此操作将会删除选择的数据，是否继续？',
    positiveText: '确定',
    negativeText: '不确定',
    onPositiveClick: () => {
      confirmDelete(item)
    },
    onNegativeClick: () => {
      // message.error('不确定')
    }
  })
}

// 删除的回调
const confirmDelete = async (item) => {
  console.log('item', item);
  const data = await handlePicture({ ids: [item.id] })
  if (data.code == 1000) {
    handleList()
    message.success('删除成功')
  } else {
    message.error('删除失败')
  }
}

// 打开编辑名称框
const handleClickTwo = (item) => {
  modelTwo.value.content = item.name
  ItemName.value = item
  showModalTwo.value = true
}

// 确定修改编辑名称框
const clickAddTwo = () => {
  formRef2.value?.validate((errors) => {
    if (!errors) {
      console.log('验证成功');
      eddItemName()
    } else {
      console.log('验证失败');
    }
  })
}

// 模态框修改名字的回调
const eddItemName = async () => {
  ItemName.value.name = modelTwo.value.content
  console.log('item', ItemName.value);
  const data = await handleditorName(ItemName.value)
  if (data.code == 1000) {
    message.success('修改成功')
    handleList()
  } else {
    message.success('修改失败')
  }
  showModalTwo.value = false
  modelTwo.value.content = ''
}

// 关闭编辑名称框
const clickCancelTwo = () => {
  showModalTwo.value = false
  modelTwo.value.content = ''
}

// 点击刷新
const clickRefresh = () => {
  handleList()
}

// 获取图片
const handlePic = async (ID) => {
  imageList.value = await getPicData(ID)
}

// 完成展开后的回调
const afterEnter = () => {
  fold.value = true
}

// 完成折叠后的回调,控制分类两个字的显隐
const afterLeave = () => {
  fold.value = false
}

// 取消新增的模态框，并且清空input框
const clickCancel = () => {
  showModal.value = false
  model.value.content = ''
}

// 新增的回调
const addItemData = async () => {
  const data = await addItemNameData({ name: model.value.content })
  console.log('data', data);
  if (data.code == 1000) {
    message.success('添加成功')
    handleList()
  } else {
    message.success('添加失败')
  }
  showModal.value = false
  model.value.content = ''
}

// 添加确认
const clickAdd = () => {
  formRef.value?.validate((errors) => {
    if (!errors) {
      console.log('验证成功');
      addItemData()
    } else {
      console.log('验证失败');
    }
  })
}

onMounted(() => {
   // 获取列表数据
  handleList()
})
</script>

<style lang="scss" scoped>
.mainBox {
  box-sizing: border-box;

  .title {
    // border: 1px solid gold;
    margin-bottom: 20px;
    font-size: 24px;
    font-weight: bold;
    color: black;
    text-align: left;
  }

  .layout-wrapper {

    // height: 80vh;
    .uploadData {
      // border: 1px solid red;
      height: 3vh;
      display: flex;
      padding: 0px 5px 0px 5px;
      align-items: center;

      .Classification {
        color: black;
      }

      .refresh {
        position: absolute;
        cursor: pointer;
        right: 35px;
        // border: 1px solid red;

      }

      .add {
        // border: 1px solid red;
        cursor: pointer;
        position: absolute;
        right: 5px;
      }
    }
  }
}


.dark .title {
  color: rgba(255, 255, 255, 0.82);
}

.dark .mainBox .layout-wrapper .uploadData .Classification {
  color: white;
}

:deep() {
  .n-menu-item-content-header {
    text-align: left !important;
  }

  .n-layout-content.n-layout.n-layout--static-positioned {
    padding: 1px !important;
  }

  // .n-menu .n-menu-item-content {
  //   padding: 0;
  // }

  .n-menu .n-menu-item-content .n-menu-item-content-header {
    .my-class {
      display: flex;
      align-items: center;
      box-sizing: border-box;
      // border: 1px solid red;
      // flex-direction: column;
      .my-title {
        font-size: 14px;
        // border: 1px solid red;
        width: 180px;
        overflow: hidden;
      }

      .includeDiv {
        // border: 1px solid red;
        width: 15px;
        height: 35px;
        margin-left: 8px;
        display: flex;
        flex-direction: column;

        .icon-1 {
          width: 100%;
          height: 50%;
          // border: 1px solid red;
          text-align: center;
          padding: 0;
          cursor: pointer;

        }

        .icon-2 {
          width: 100%;
          height: 50%;
          // border: 1px solid red;
          text-align: center;
          padding: 0;
          cursor: pointer;
        }

        .icon-1:hover {
          color: red;
        }

        .icon-2:hover {
          color: red;
        }
      }

      .my-button {
        border: 1px solid red;
        font-size: 8px;
        display: inline-block;
        height: 15px;
        width: 20px;
        text-align: center;
        position: absolute;
        top: 25%;
        right: 0;
        z-index: 999;
        // text-align: right;
      }

      .my-button:hover {
        color: red;
      }
    }
  }

  // .n-layout-sider.n-layout-sider--show-content .n-layout-sider-scroll-container {
  // background-color: rgba(16, 16, 20,0);
  // background-color: none !important;
  // }

  .n-layout-sider {
    background-color: transparent;
  }
}
</style>
